package com.cgsd.heyu;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;

import com.android.library.utils.LogUtils;
import com.android.library.utils.SharedPreferencesHelper;
import com.android.library.utils.ToastHelper;
import com.bun.miitmdid.core.JLibrary;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.CommonConfig;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.utils.AESUtils;
import com.cgsd.heyu.utils.ALiPayUtil;
import com.cgsd.heyu.utils.MiitHelper;
import com.cgsd.heyu.utils.MyFileNameGenerator;
import com.cgsd.heyu.utils.PreferencesUtils;
import com.danikula.videocache.HttpProxyCacheServer;
import com.hztz.kankanzhuan.KanNewsSDK;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.pceggs.workwall.util.PceggsWallUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.Bugly;
import com.tencent.tinker.loader.app.TinkerApplication;
import com.tencent.tinker.loader.shareutil.ShareConstants;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.bmob.v3.Bmob;
import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;


/**
 * @author Created by Administrator on 2018/3/24.
 */

public class App extends TinkerApplication {
    private static App mApp;
    private UserModeConfig userModeConfig;
    private CommonConfig commonConfig;
    // 抖音模块缓存
    private HttpProxyCacheServer proxy;

    public App() {
        super(ShareConstants.TINKER_ENABLE_ALL, "com.cgsd.heyu.AppLike",
                "com.tencent.tinker.loader.TinkerLoader", false);
    }

    public static HttpProxyCacheServer getProxy(Context context) {
        App app = (App) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        AESUtils.init("hooyun2360656989");
        //初始化Toast
        ToastHelper.init(mApp);
        //设置全局数据
        new SharedPreferencesHelper(this);
        //新闻
        KanNewsSDK.init(this);
        //友盟相关
        initUmeng();
        //异步初始化数据
        initThirdService();
        //初始化广告
        initAd();
        //用户数据
        userModeConfig = new UserModeConfig();
        //配置数据
        commonConfig = new CommonConfig();
        //设置日志的显示
        LogUtils.showLog(BuildConfig.DEBUG);

        //初始化bugly
        //Bugly.init(getApplicationContext(), "93c24dc411", BuildConfig.DEBUG);
        Bmob.initialize(getApplicationContext(), "47e9c00d761fa3b4eb3380cba995855f");

        PceggsWallUtils.init(this);
        initOAID();

        initOkGo();
        initLog();

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }
    private void initOAID() {
        if (Build.VERSION.SDK_INT>28) {
            JLibrary.InitEntry(this);
            try {
                MiitHelper miitHelper = new MiitHelper(appIdsUpdater);
                miitHelper.getDeviceIds(getApplicationContext());
            } catch (Exception e) {
                e.printStackTrace();
                com.apkfuns.logutils.LogUtils.e("initOAID"+e.getMessage());
            }
        }else {
            com.apkfuns.logutils.LogUtils.e("77777777777777777");
        }
    }

    private MiitHelper.AppIdsUpdater appIdsUpdater = new MiitHelper.AppIdsUpdater() {
        @Override
        public void OnIdsAvalid(@NonNull String ids) {
            com.apkfuns.logutils.LogUtils.e("initOAID"+"设备号:"+ids);
            if (!TextUtils.isEmpty(ids)){
                PreferencesUtils.put("oaid",ids);
            }
        }
    };

    private void initLog() {
        com.apkfuns.logutils.LogUtils.getLogConfig()
                .configAllowLog(true)
                .configTagPrefix(getString(R.string.app_name))
                .configShowBorders(true)
                .configFormatTag("%d{HH:mm:ss:SSS} %t %c{-5}");
    }

    public UserModeConfig getUserModeConfig() {
        return userModeConfig;
    }

    public CommonConfig getCommonConfig() {
        return commonConfig;
    }

    public void setUserModeConfig(UserModeConfig userModeConfig) {
        this.userModeConfig = userModeConfig;
    }

    public void setCommonConfig(CommonConfig commonConfig) {
        this.commonConfig = commonConfig;
    }

    private void initAd() {
        //穿山甲
        TTAdSdk.init(this,
                new TTAdConfig.Builder()
                        .appId(AppConfig.AD_C_ID)
//                        .appId("5152222")//正式
//                        .appId("5141291")//测试
                        .useTextureView(true)
                        .appName(getString(R.string.app_name))
                        //落地页主题
                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
                        //是否允许sdk展示通知栏提示
                        .allowShowNotify(true)
                        //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                        .debug(BuildConfig.DEBUG)
                        //允许直接下载的网络状态集合,没有设置的网络下点击下载apk会有二次确认弹窗，弹窗中会披露应用信息
                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI)
                        //是否支持多进程，true支持
                        .supportMultiProcess(false)
                        //是否异步初始化sdk,设置为true可以减少SDK初始化耗时
                        .asyncInit(true)
                        //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
                        .build());
    }

    public static App getInstance() {
        return mApp;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    /**
     * 初始化友盟相关
     */
    private void initUmeng() {
//        // 初始化SDK
//        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "6eb2974424b78504831d9bf4e014280c");
//        // 选用AUTO页面采集模式
//        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_MANUAL);
//        UMConfigure.setLogEnabled(true);

//        //微信
//        PlatformConfig.setWeixin("wxef5f2c5deeff0872", "cf03e38678877a4fa4e4ca97acfcb704");
//        PlatformConfig.setWXFileProvider("com.tencent.sample2.fileprovider");
//        //支付宝
//        PlatformConfig.setAlipay("2015111700822536");
    }

    /**
     * 初始化延迟服务
     */
    private void initThirdService() {
        /**设置全局的Header构建器*/
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //全局设置主题颜色
                layout.setPrimaryColorsId(R.color.white, R.color.black);
                //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context);
            }
        });
        /**设置全局的Footer构建器*/
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context);
            }
        });
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .fileNameGenerator(new MyFileNameGenerator()).build();
    }

    /**
     * 原本框架不能上传文件，只能使用OKgo
     */
    private void initOkGo() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);

        //okGo网络框架初始化和全局配置
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(loggingInterceptor);
        // builder.proxy(Proxy.NO_PROXY);
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));//使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.readTimeout(3000000, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(3000000, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(3000000, TimeUnit.MILLISECONDS);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
//        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
//        headers.put("commonHeaderKey2", "commonHeaderValue2");
        //设置请求参数
        HttpParams params = new HttpParams();
//        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
//        params.put("commonParamsKey2", "这里支持中文参数");
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3)                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0

                .addCommonHeaders(headers)                      //全局公共头
                .addCommonParams(params);
    }

}
